package com.minimalist.gateway.filter;

import io.micrometer.core.instrument.Timer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.time.Instant;

/**
 * 请求耗时统计过滤器
 *
 * @author minimalist
 */
@Component
public class RequestTimeFilter implements GlobalFilter, Ordered{
    private static final Logger log = LoggerFactory.getLogger(RequestTimeFilter.class);


    private static final String REQUEST_TIME_BEGIN = "requestTimeBegin";

    @Autowired
    private Timer requestLatencyTimer;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain){
        // 记录请求开始时间
        exchange.getAttributes().put(REQUEST_TIME_BEGIN, Instant.now());

        // 请求结束后计算耗时
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            Instant startTime = exchange.getAttribute(REQUEST_TIME_BEGIN);
            if (startTime != null){
                Duration duration = Duration.between(startTime, Instant.now());
                // 在计算耗时的部分添加
                requestLatencyTimer.record(duration);
                ServerHttpRequest request = exchange.getRequest();
                String path = request.getURI().getPath();
                String method = request.getMethod().name();

                // 记录请求耗时日志
                log.info("请求路径: {} {}, 耗时: {}ms", method, path, duration.toMillis());

                // 在响应头中添加请求耗时信息
//                exchange.getResponse().getHeaders().add("X-Response-Time", duration.toMillis() + "ms");
            }
        }));
    }

    @Override
    public int getOrder(){
        // 设置为最高优先级，确保最先执行记录开始时间，最后执行记录结束时间
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
